﻿using BCCommon;
using BCEntity.TMS.InsuredConfig;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using BCCommon.TMS.Insured;
using System.Data;

namespace BCData.TMS.InsuredConfig
{
    public class InsuredConfigData : IInsuredConfigData
    {
		private readonly IDatabaseContext database;

		private const string QUERY = @"SELECT
								InsuredConfigId,
								InsuredType,
								InsuredTypeStr,
								VehicleTransportBusinessConfigId,
								MinAmount,
								MaxAmount,
								InsuredFeeRatio,
								CreateAdminId,
								CreateAdminName,
								CreateTime,
								UpdateTime,
								EditAdminId,
								EditAdminName 
							FROM
								InsuredConfig";

        private const string QUERY_JOIN = @"SELECT
								A.InsuredConfigId,
								A.InsuredType,
								A.InsuredTypeStr,
								A.VehicleTransportBusinessConfigId,
								A.MinAmount,
								A.MaxAmount,
								A.InsuredFeeRatio,
								A.CreateAdminId,
								A.CreateAdminName,
								A.CreateTime,
								A.UpdateTime,
								A.EditAdminId,
								A.EditAdminName,
                                B.TransportBusiness,
                                B.BusinessOrder,
                                B.Remark,
                                B.Enabled 
							FROM InsuredConfig A
                            INNER JOIN VehicleTransportBusinessConfig B ON A.VehicleTransportBusinessConfigId = B.VehicleTransportBusinessConfigId";

        public InsuredConfigData(IDatabaseContext database)
        {
            this.database = database;
        }

        public async Task<InsuredConfigEntity> Insert(InsuredConfigEntity entity)
        {
			return await database.Master.InsertAsync(entity);
        }

        public async Task<InsuredConfigEntity> GetEntity(int insuredConfigId)
        {
			return await database.Slave.QueryEntityAsync<InsuredConfigEntity>($"{QUERY} WHERE InsuredConfigId = ?InsuredConfigId", new { insuredConfigId });
        }

        public async Task<InsuredConfigEntity> Update(InsuredConfigEntity entity)
        {
			return await database.Master.UpdateAsync(entity);
        }

        public async Task<int> Delete(int insuredConfigId)
        {
            return await database.Master.ExecuteAsync("DELETE FROM InsuredConfig WHERE InsuredConfigId = ?InsuredConfigId", new { insuredConfigId });
        }

        public async Task<(IEnumerable<InsuredConfigViewEntity>, int)> Query(InsuredType? insuredType, int? vehicleTransportBusinessConfigId, DateTime? createStartDate, DateTime? createEndDate, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (insuredType.HasValue)
            {
                wheres.Add("A.InsuredType = ?InsuredType");
                parameters.Add("?InsuredType", insuredType.Value.ToString(), DbType.AnsiString);
            }
            if (vehicleTransportBusinessConfigId.HasValue)
            {
                wheres.Add("A.VehicleTransportBusinessConfigId = ?VehicleTransportBusinessConfigId");
                parameters.Add("?VehicleTransportBusinessConfigId", vehicleTransportBusinessConfigId.Value, DbType.Int32);
            }
            if (createStartDate.HasValue)
            {
                wheres.Add("A.CreateTime >= ?CreateStartDate");
                parameters.Add("?CreateStartDate", createStartDate.Value.Date, DbType.Date);
            }
            if (createEndDate.HasValue)
            {
                wheres.Add("A.CreateTime < ?CreateEndDate");
                parameters.Add("?CreateEndDate", createEndDate.Value.AddDays(1).Date, DbType.Date);
            }
            string sql = string.Format(@"{0} {1} ORDER BY A.InsuredConfigId DESC LIMIT {2},{3};
                    SELECT COUNT(1) FROM InsuredConfig A {1}",
                    QUERY_JOIN,
                    wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : string.Empty,
                    (pageIndex - 1) * pageSize,
                    pageSize);
            return await database.Slave.QueryPageableListAsync<InsuredConfigViewEntity>(sql, parameters);
        }

        public async Task<IEnumerable<InsuredConfigViewEntity>> GetList(InsuredType? insuredType, int? vehicleTransportBusinessConfigId)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (insuredType.HasValue)
            {
                wheres.Add("A.InsuredType = ?InsuredType");
                parameters.Add("?InsuredType", insuredType.Value.ToString(), DbType.AnsiString);
            }
            if (vehicleTransportBusinessConfigId.HasValue)
            {
                wheres.Add("A.VehicleTransportBusinessConfigId = ?VehicleTransportBusinessConfigId");
                parameters.Add("?VehicleTransportBusinessConfigId", vehicleTransportBusinessConfigId.Value, DbType.Int32);
            }
            string sql = string.Format("{0} {1} ORDER BY A.InsuredConfigId DESC", QUERY_JOIN, wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : string.Empty);
            return await database.Slave.QueryAsync<InsuredConfigViewEntity>(sql, parameters);
        }
    }
}
